package cn.itcast.bos.utils;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.service.system.UserService;
//用户登录
@Service("bosRealms")
public class BosRealms extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		System.out.println("授权管理");
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		//根据用户获取对应的角色，添加角色
		List<Role> list = roleService.findByUser(user);
		for (Role role : list) {
			simpleAuthorizationInfo.addRole(role.getKeyword());
		}
		//根据用户获取对应的权限，添加权限
		List<Permission> list1 = permissionService.findByUser(user);
		for (Permission permission : list1) {
			simpleAuthorizationInfo.addStringPermission(permission.getKeyword());
		}
		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
		System.out.println("认证管理");
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) at;
		User user = userService.findByUsername(usernamePasswordToken.getUsername());
		if(user==null){
			//用户为空
			return null;
		}else{
			return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
		}
	}

}
